package com.zt.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.reggie.common.Constant;
import com.zt.reggie.common.R;
import com.zt.reggie.dto.DishDto;
import com.zt.reggie.entity.Category;
import com.zt.reggie.entity.Dish;
import com.zt.reggie.entity.DishFlavor;
import com.zt.reggie.service.CategoryService;
import com.zt.reggie.service.DishFlavorService;
import com.zt.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec com.zt.reggie.controller
 * @since 2023 - 02 - 26 - 10:24
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理缓存
        String key = Constant.REDIS_DISH_PREFIX + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功!");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name){
        //分页查 dish表
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Dish::getName, name);
        wrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo, wrapper);

        //需要返回分类名称
        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        //records
        List<DishDto> list = pageInfo.getRecords().stream().map((item) -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item, dto);
            //设置 categoryName
            Long id = item.getCategoryId();
            Category category = categoryService.getById(id);
            if(category != null)
                dto.setCategoryName(category.getName());
            return dto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 获取菜品基本信息和其口味信息
     * 用于修改回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品基本信息和其口味信息
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
//        //方式1：清理所有菜品的缓存数据
//        String pattern = Constant.REDIS_DISH_PREFIX + "*";
//        Set<Object> keys = redisTemplate.keys(pattern);
//        if(keys != null)
//            redisTemplate.delete(keys);
        //方式2：精确清理菜品分类
        String key = Constant.REDIS_DISH_PREFIX + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("修改菜品成功!");
    }

    /**
     * 根据id 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> ids){
        dishService.deleteWithFlavor(ids);

        return R.success("删除菜品成功!");
    }

    /**
     * 根据id 批量停售/起售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> change(@PathVariable("status") Integer status, @RequestParam("ids") List<Long> ids){
        dishService.changeStatus(ids, status);
        return R.success("操作成功!");
    }

    /**
     * 根据分类 查询菜品信息， 添加套餐时使用
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList = null;
        //先从redis中获取缓存数据
        String key = Constant.REDIS_DISH_PREFIX + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtoList = (List<DishDto>)redisTemplate.opsForValue().get(key);
        //缓存中不存在，查数据库，添加到缓存
        if(dishDtoList != null) return R.success(dishDtoList);

        //构造查询条件:
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        wrapper.eq(Dish::getStatus, 1);
        //排序
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishService.list(wrapper);
        //前台用户菜品显示 需要口味信息
        dishDtoList = dishList.stream().map(e ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(e, dishDto);
            Long dishId = e.getId();
            //查口味
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, dishId);
            dishDto.setFlavors(dishFlavorService.list(queryWrapper));
            return dishDto;
        }).collect(Collectors.toList());

        //缓存
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
